<template>
  <div class="member-container">
      <div class="weui-cells-no-margin" v-for="(member, index) in this.members" :key="index">
          <div class="weui-cells__title"  slot="after-title">
            家庭成员: {{ member.user_name }}
            <span v-if="index>0" class="delete-member" @click="deleteMember(index)">删除</span>
            <span class="add-member" :class="{'add-mem-padd': index > 0}" @click="attachAMember()">添加</span>
          </div>
          <group>
              <x-input
              :class="{'weui-cell_warn': $v.members.$each[index].user_name.$error }"
              title="成员姓名"
              :id="'user_name'+index"
              v-model="member.user_name"
              placeholder="输入成员姓名"
              placeholder-align="right"
              @on-change="formDataChange"
              :show-clear="false" @on-blur="onBlur">
              </x-input>

              <x-input
              :class="{'weui-cell_warn': $v.members.$each[index].mobile_num.$error }"
              :id="'mobile_num'+index"
              title="手机号码"
              @on-change="formDataChange"
              v-model="member.mobile_num"
              placeholder="手机号码"
              placeholder-align="right"
              :show-clear="false" @on-blur="onBlur">
              </x-input>

              <selector
              direction="rtl"
              title="性别"
              :class="{'weui-cell_warn': $v.members.$each[index].user_sex.$error }"
              v-model="members[index].user_sex"
              @on-change="changeUserSex(members[index].user_sex, index)"
              placeholder="选择性别"
              :options="memberGenderOptions"
              placeholder-align="right">
              </selector>

              <x-input
              :class="{'weui-cell_warn': $v.members.$each[index].user_role.$error }"
              title="与宝宝的关系"
              v-model="members[index].user_other_role"
              @on-change="userOtherRole(members[index].user_other_role, index)"
              placeholder="输入与宝宝的关系"
              placeholder-align="right"
              :show-clear="false">
              </x-input>

              <selector
              direction="rtl"
              title="宝宝关系选择"
              v-model="members[index].user_native_role"
              @on-change="changeUserRole(members[index].user_native_role, index)"
              placeholder="选择与宝宝的关系"
              :options="memberRoleOptions"
              placeholder-align="right">
              </selector>

          </group>
        </div>
  </div>
</template>

<script>
import Vue from 'vue'
import Group from 'vux/src/components/group'
import { mobile, nonString } from '../lib/validator'
import XInput from 'vux/src/components/x-input'
import Selector from 'vux/src/components/selector'
import Datetime from 'vux/src/components/datetime'

import { validationMixin } from 'vuelidate'
import { required, minLength } from 'vuelidate/lib/validators'

export default {
  mixins: [validationMixin],
  props: {
    values: {
      type: Array
    }
  },
  mounted () {
    // console.log(values)
    if (!this.members.length) {
      this.attachAMember()
    }
  },
  watch: {
    values (values) {
      if (!this.init) {
        const members = [];
        [].concat(values || []).forEach((elem, index) =>
        {
          const userRoleValue = '' + elem.user_role
          members.push(Object.assign({}, this.default, elem, {
              user_other_role: userRoleValue,
              user_native_role: userRoleValue
            }
          ))
        })
        this.members = members
        if (!this.members.length) {
          this.attachAMember()
        }
        this.init = true
      }
    }
  },
  components:{
    XInput,
    Group,
    Selector,
    Datetime
  },
  methods: {
    refreshMembers (members) {
      this.members = this.members.concat([])
    },
    changeUserRole (userRole, index) {
      const userRoleVulue = userRole === '其他' ? '' : userRole;

      this.userRoles = Object.assign({}, this.userRoles, {[index]: {
          user_role: userRoleVulue
        }
      })

      this.members[index] = Object.assign(
        {}, this.members[index], {
          user_role: userRoleVulue,
          user_other_role: userRoleVulue,
          user_native_role: userRole
        }
      )

      this.refreshMembers();
      // console.log(userRole === '其他' ? '' : userRoleVulue, userRole, JSON.stringify(this.members[index]))
      this.formDataChange();
    },
    changeUserSex (userSex, index) {
      this.members[index] = Object.assign(
        {}, this.members[index], {
          user_sex: userSex
      })
      this.formDataChange();
      this.refreshMembers();
    },
    userOtherRole (userOtherRoleValue, index) {
      const user_native_role = this.memberRoleOptions.indexOf(userOtherRoleValue)
        > -1 ? userOtherRoleValue : '其他'

      if (userOtherRoleValue) {
        this.members[index] = Object.assign(
          this.members[index], {
            user_role: userOtherRoleValue,
            user_other_role: userOtherRoleValue,
            user_native_role: user_native_role
          }
        )
      } else {
        this.members[index] = Object.assign(
          this.members[index], {
            user_other_role: userOtherRoleValue,
            user_native_role: user_native_role
          }
        )
      }
      this.refreshMembers();
      this.formDataChange();
    },
    formDataChange () {
      const values = []
      this.members.forEach((element, index) => {
        const member = {}
        Object.keys(this.fields).forEach((property) => {
          member[property] = element[property]
        })
        values.push(member)
      })
      this.$emit('on-change', values);
    },
    addMember (index) {
    },
    attachAMember () {
      this.members.push(Object.assign({}, this.default))
    },
    deleteMember (index) {
      this.members.splice(index, 1)
    },
    onBlur () {
    }
  },
  validations () {
    const data = this.members[0];
    if (data.user_name || data.mobile_num
     || this.members.length > 1)
    {
      return {
        members: {
          required,
          $each: {
            user_name: {
              required,
              minLength: minLength(2)
            },
            mobile_num: {
              mobile: mobile()
            },
            user_sex: {
              required
            },
            user_role: {
              required
            },
            user_other_role: {
              required,
              minLength: minLength(2)
            }
          }
        }
      }
    } else {
      return {
        members: {
          required,
          $each: {
            user_name: {
            },
            mobile_num: {
            },
            user_sex: {
            },
            user_role: {
            },
            user_other_role: {
            }
          }
        }
      }
    }
  },
  data () {
    const fields = {
        user_name: '',
        user_sex: '',
        user_role: '',
        mobile_num: '',
    };

    let defaultFields = Object.assign({}, fields, {
        user_other_role: '',
        user_native_role: ''
    });

    return {
      userRole: '',
      userOtherRoleValue: '',
      userOtherRoles: {},
      userSex: '',
      userRoles: {},
      members: [],
      fields: fields,
      default: defaultFields,
      memberGenderOptions: [
        {
          key : 'MALE###',
          value: '男'
        },
        {
          key: 'FEMALE#',
          value: '女'
        }
      ],
      memberRoleOptions: [
        '爸爸', '妈妈', '爷爷', '奶奶', '外公', '外婆',
        '叔叔', '阿姨', '姐姐', '妹妹','其他'
      ]
    }
  }
}
</script>

<style lang='less'>
  @import "../less/index.less";
  .member-container {
    .add-member {
      float: right;
      color: #39ADFF;
    }

    .add-mem-padd {
      margin-right: 20px;
    }

    .delete-member {
      float: right;
      color: #39ADFF;
    }
  }
</style>
